from auth import db
from settings import settings
from fastapi_jwt_auth import AuthJWT
from datetime import datetime, timedelta
from auth.utilities import authenticate_user
from fastapi import HTTPException, Depends,APIRouter
from fastapi.security import OAuth2PasswordRequestForm

auth_router = APIRouter(prefix='/auth',
                        tags=['auth'])


@AuthJWT.load_config
def get_config():
    return settings


@auth_router.post('/login')
def login(auth: OAuth2PasswordRequestForm = Depends(), authorize: AuthJWT = Depends()):
    if not(authenticate_user(auth.username, auth.password)):
        raise HTTPException(status_code=401, detail="Bad username or password")

    user_role = db.get_user_role(auth.username)
    access_token = authorize.create_access_token(subject=auth.username, expires_time=timedelta(minutes=16))
    refresh_token = authorize.create_refresh_token(subject=auth.username, expires_time=timedelta(days=1))
    return {"access_token": access_token, "refresh_token": refresh_token, "user_role": user_role}


@auth_router.post('/refresh')
def refresh(authorize: AuthJWT = Depends()):
    authorize.jwt_refresh_token_required()

    current_user = authorize.get_jwt_subject()
    new_access_token = authorize.create_access_token(subject=current_user, expires_time=timedelta(minutes=16))
    return {"access_token": new_access_token}
